﻿using HomagGroup.Base.UI.Windows;
using System.Collections.Generic;
using System.Windows.Media;
using System.Windows;
using System;
using System.Windows.Controls;
using HomagGroup.Base.UI;

namespace HomagChina.Nesting.Views
{
    /// <summary>
    /// TransHistory.xaml 的交互逻辑
    /// </summary>
    public partial class PrintHistoryDialog : Dialog
    {
        private PrintHistoryDialogViewModel _viewModel;

        public PrintHistoryDialog()
        {
            InitializeComponent();
            var RouterDictionary = (Dictionary<string, RouterItemDataModel>)Application.Current.Properties["RouterMap"];
            HomeViewModel homeViewModel = RouterDictionary["1"].userControl.DataContext as HomeViewModel;
            _viewModel = homeViewModel.printHistoryDialogViewModel;
            // 订阅 ViewModel 的事件
            _viewModel.RequestScrollPositionSave += ViewModel_RequestScrollPositionSave;
            _viewModel.RequestScrollPositionRestore += ViewModel_RequestScrollPositionRestore;
        }

        private void ViewModel_RequestScrollPositionSave(object sender, EventArgs e)
        {
            SaveScrollPosition();
        }

        private void ViewModel_RequestScrollPositionRestore(object sender, EventArgs e)
        {
            RestoreScrollPosition();
        }

        private void SaveScrollPosition()
        {
            var scrollViewer = VisualTreeHelperExtensions.FindVisualChild<ScrollViewer>(MyDataTable);
            if (scrollViewer != null)
            {
                _viewModel.VerticalOffset = scrollViewer.VerticalOffset;
            }
        }

        private void RestoreScrollPosition()
        {
            var scrollViewer = VisualTreeHelperExtensions.FindVisualChild<ScrollViewer>(MyDataTable);
            if (scrollViewer != null)
            {
                scrollViewer.ScrollToVerticalOffset(_viewModel.VerticalOffset);
            }
        }
    }

    public static class VisualTreeHelperExtensions
    {
        public static T FindVisualChild<T>(DependencyObject parent) where T : DependencyObject
        {
            if (parent == null) return null;

            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
            {
                var child = VisualTreeHelper.GetChild(parent, i);
                if (child is T foundChild)
                {
                    return foundChild;
                }
                var childOfChild = FindVisualChild<T>(child);
                if (childOfChild != null)
                {
                    return childOfChild;
                }
            }
            return null;
        }
    }
}